document.addEventListener('DOMContentLoaded', function() {
    const usersTableBody = document.getElementById('usersTableBody');
    const selectedUser = document.getElementById('selectedUser');
    const permissionForm = document.getElementById('permissionForm');
    const totalUsers = document.getElementById('totalUsers');
    const adminCount = document.getElementById('adminCount');
    const registeredCount = document.getElementById('registeredCount');
    const guestCount = document.getElementById('guestCount');
    const operationLog = document.getElementById('operationLog');
    
    // 初始化页面
    loadUsersList();
    loadOperationLog();
    loadGuestUserCount();
    loadTotalUserCount();
    
    // 权限管理表单提交
    permissionForm.addEventListener('submit', function(e) {
        e.preventDefault();
        updateUserPermission();
    });
    
    function loadUsersList() {
        // 从后端获取用户数据
        fetch('http://localhost:3000/api/users', {
            headers: {
                'Authorization': sessionStorage.getItem('token') || ''
            }
        })
        .then(async res => {
            let text = await res.text();
            let users;
            try {
                users = JSON.parse(text);
            } catch (e) {
                console.error('用户列表解析JSON失败:', e, text);
                users = null;
            }
            console.log('用户列表响应状态:', res.status, '内容:', users);
            if (res.ok && Array.isArray(users)) {
                let html = '';
                users.forEach(user => {
                    html += `
                        <tr>
                            <td>${user.username}</td>
                            <td>${user.email || '-'}</td>
                            <td><span class="role-badge role-${user.role}">${getRoleName(user.role)}</span></td>
                            <td>${formatDate(user.created_at)}</td>
                            <td>${user.last_login ? formatDate(user.last_login) : '-'}</td>
                            <td class="user-actions">
                                <button class="btn btn-primary btn-sm" onclick="editUser('${user.username}')">编辑</button>
                                <button class="btn btn-danger btn-sm" onclick="deleteUser('${user.username}')">删除</button>
                            </td>
                        </tr>
                    `;
                });
                usersTableBody.innerHTML = html;
                updateUserSelect(users);
                updateUserStats(users);
            } else {
                usersTableBody.innerHTML = '<tr><td colspan="6">无法获取用户数据</td></tr>';
                updateUserSelect([]);
                updateUserStats([]);
                console.error('loadUsersList: 用户数据异常', {status: res.status, users, text});
                showCenterModal('【用户列表异常】' + ((users && users.error) || '获取用户列表失败'));
            }
        })
        .catch(err => {
            console.error('loadUsersList: 用户列表fetch异常:', err);
            usersTableBody.innerHTML = '<tr><td colspan="6">无法获取用户数据</td></tr>';
            updateUserSelect([]);
            updateUserStats([]);
            showCenterModal('【用户列表fetch异常】网络错误，获取用户列表失败');
        });
    }
    
    function getRoleName(role) {
        const roleNames = {
            'admin': '管理员',
            'registered': '注册用户',
            'guest': '普通用户'
        };
        return roleNames[role] || role;
    }
    
    function formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', {hour: '2-digit', minute: '2-digit'});
    }
    
    function updateUserSelect(users) {
        let html = '<option value="">请选择用户</option>';
        users.forEach(user => {
            html += `<option value="${user.username}">${user.username} (${getRoleName(user.role)})</option>`;
        });
        selectedUser.innerHTML = html;
    }
    
    function updateUserStats(users) {
        // 只更新管理员和注册用户数量，普通用户和总用户数用单独接口
        adminCount.textContent = users.filter(u => u.role === 'admin').length;
        registeredCount.textContent = users.filter(u => u.role === 'registered').length;
    }
    
    function loadGuestUserCount() {
        fetch('http://localhost:3000/api/guest-user', {
            headers: {
                'Authorization': sessionStorage.getItem('token') || ''
            }
        })
        .then(res => res.json())
        .then(data => {
            guestCount.textContent = data.normalUserCount || 0;
        })
        .catch(err => {
            console.error('获取普通用户数量失败:', err);
            guestCount.textContent = '0';
        });
    }
    
    function loadTotalUserCount() {
        fetch('http://localhost:3000/api/total-user', {
            headers: {
                'Authorization': sessionStorage.getItem('token') || ''
            }
        })
        .then(res => res.json())
        .then(data => {
            totalUsers.textContent = data.totalUserCount || 0;
        })
        .catch(err => {
            console.error('获取总用户数失败:', err);
            totalUsers.textContent = '0';
        });
    }
    
    function loadOperationLog() {
        fetch('http://localhost:3000/api/operation-logs', {
            headers: {
                'Authorization': sessionStorage.getItem('token') || ''
            }
        })
        .then(res => res.json())
        .then(logs => {
            let html = '';
            logs.forEach(log => {
                html += `
                    <div class="log-item">
                        <span class="log-time">${formatDate(log.created_at)}</span>
                        <span class="log-action">${log.action}</span>
                        <span class="log-details">${log.details}${log.operator ? '（操作者：' + log.operator + '）' : ''}</span>
                    </div>
                `;
            });
            operationLog.innerHTML = html;
        })
        .catch(err => {
            operationLog.innerHTML = '<div class="log-item">无法获取操作日志</div>';
        });
    }
    
    function getMockLogs() {
        return [
            {
                time: new Date().toISOString(),
                action: '权限更新',
                details: '用户 testuser1 角色从 普通用户 更改为 注册用户'
            },
            {
                time: new Date(Date.now() - 3600000).toISOString(),
                action: '用户登录',
                details: '用户 admin 登录系统'
            },
            {
                time: new Date(Date.now() - 7200000).toISOString(),
                action: '用户注册',
                details: '新用户 testuser2 注册成功'
            },
            {
                time: new Date(Date.now() - 10800000).toISOString(),
                action: '权限更新',
                details: '用户 user 角色从 普通用户 更改为 注册用户'
            }
        ];
    }
    
    async function updateUserPermission() {
        const username = selectedUser.value;
        const newRole = document.getElementById('newRole').value;
        // 获取当前选中用户的角色
        const selectedOption = selectedUser.options[selectedUser.selectedIndex];
        const isAdmin = selectedOption && selectedOption.textContent.includes('管理员');
        if (!username) {
            alert('请选择用户！');
            return;
        }
        if (!newRole) {
            alert('请选择新角色！');
            return;
        }
        if (isAdmin) {
            showCenterModal('管理员账号不能更改角色！');
            return;
        }
        try {
            const res = await fetch('http://localhost:3000/api/users/role', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': sessionStorage.getItem('token') || ''
                },
                body: JSON.stringify({ username, newRole })
            });
            const data = await res.json();
            if (res.ok) {
                showCenterModal('用户权限更新成功！');
                permissionForm.reset();
                loadUsersList();
                loadOperationLog();
            } else {
                alert(data.error || '更新失败');
            }
        } catch (err) {
            alert('网络错误，更新失败');
        }
    }
    
    function addOperationLog(action) {
        const log = {
            time: new Date().toISOString(),
            action: '权限更新',
            details: action
        };
        
        // 在实际项目中，这里会保存到后端
        console.log('操作日志:', log);
    }
    
    // 编辑用户弹窗逻辑
    const editUserModal = document.getElementById('editUserModal');
    const editUserForm = document.getElementById('editUserForm');
    const editUsername = document.getElementById('editUsername');
    const editEmail = document.getElementById('editEmail');
    // const editRole = document.getElementById('editRole'); // 移除角色
    const cancelEditUserBtn = document.getElementById('cancelEditUserBtn');

    window.editUser = async function(username) {
        // 获取用户信息
        try {
            const res = await fetch('http://localhost:3000/api/users', {
                headers: { 'Authorization': sessionStorage.getItem('token') || '' }
            });
            const users = await res.json();
            const user = users.find(u => u.username === username);
            if (!user) {
                alert('用户不存在！');
                return;
            }
            if (user.role === 'admin') {
                showCenterModal('管理员账号不能编辑！');
                return;
            }
            editUsername.value = user.username;
            editEmail.value = user.email || '';
            window.originalUserEmail = user.email || '';
            // editRole.value = user.role; // 移除角色
            editUserModal.style.display = 'flex';
        } catch (err) {
            alert('获取用户信息失败');
        }
    };

    cancelEditUserBtn.onclick = function() {
        editUserModal.style.display = 'none';
    };

    editUserForm.onsubmit = async function(e) {
        e.preventDefault();
        const username = editUsername.value;
        const email = editEmail.value;
        // const role = editRole.value; // 移除角色
        if (!username || !email) {
            alert('请填写完整信息');
            return;
        }
        if (email === window.originalUserEmail) {
            showCenterModal('未做任何更改，无需保存');
            return;
        }
        try {
            const res = await fetch('http://localhost:3000/api/users/update', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': sessionStorage.getItem('token') || ''
                },
                body: JSON.stringify({ username, email }) // 只传用户名和邮箱
            });
            const data = await res.json();
            if (res.ok) {
                alert('用户信息更新成功！');
                editUserModal.style.display = 'none';
                loadUsersList();
            } else {
                alert(data.error || '更新失败');
            }
        } catch (err) {
            alert('网络错误，更新失败');
        }
    };
    
    // 新增用户弹窗逻辑
    const addUserBtn = document.getElementById('addUserBtn');
    const addUserModal = document.getElementById('addUserModal');
    const addUserForm = document.getElementById('addUserForm');
    const cancelAddUserBtn = document.getElementById('cancelAddUserBtn');

    if (addUserBtn && addUserModal && addUserForm && cancelAddUserBtn) {
        addUserBtn.onclick = function() {
            addUserModal.style.display = 'flex';
            addUserForm.reset();
        };
        cancelAddUserBtn.onclick = function() {
            addUserModal.style.display = 'none';
        };
        addUserModal.onclick = function(e) {
            if (e.target === addUserModal) addUserModal.style.display = 'none';
        };
        addUserForm.onsubmit = async function(e) {
            e.preventDefault();
            const username = document.getElementById('addUsername').value.trim();
            const email = document.getElementById('addEmail').value.trim();
            const password = document.getElementById('addPassword').value;
            // 简单校验
            if (!username) {
                showCenterModal('请输入用户名！'); return;
            }
            if (!email || !/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/.test(email)) {
                showCenterModal('请输入有效的邮箱！'); return;
            }
            if (!password || password.length < 6) {
                showCenterModal('密码长度不能少于6位！'); return;
            }
            // 请求注册接口
            try {
                const res = await fetch('http://localhost:3000/api/register', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ username, email, password })
                });
                const data = await res.json();
                if (res.ok) {
                    showCenterModal('新增用户成功！');
                    addUserModal.style.display = 'none';
                    loadUsersList();
                } else {
                    showCenterModal(data.error || '新增用户失败');
                }
            } catch (err) {
                showCenterModal('新增用户失败，服务器异常');
            }
        };
    }
    
    // 全局函数供HTML调用
    window.deleteUser = async function(username) {
        // 先查找该用户的角色
        try {
            const res = await fetch('http://localhost:3000/api/users', {
                headers: { 'Authorization': sessionStorage.getItem('token') || '' }
            });
            const users = await res.json();
            const user = users.find(u => u.username === username);
            if (!user) {
                showCenterModal('用户不存在！');
                return;
            }
            if (user.role === 'admin') {
                showCenterModal('不能删除管理员账号！');
                return;
            }
        } catch (err) {
            showCenterModal('获取用户信息失败');
            return;
        }
        showCenterConfirm(`确定要删除用户 ${username} 吗？`, async function(ok) {
            if (ok) {
                try {
                    const res = await fetch(`http://localhost:3000/api/users/${username}`, {
                        method: 'DELETE',
                        headers: { 'Authorization': sessionStorage.getItem('token') || '' }
                    });
                    let data = {};
                    try {
                        data = await res.json();
                    } catch (e) {
                        data = {};
                    }
                    if (res.ok) {
                        showCenterModal('删除成功！');
                        loadUsersList();
                    } else {
                        showCenterModal(data.error || '删除失败');
                    }
                } catch (err) {
                    showCenterModal('删除失败，服务器异常');
                }
            }
        });
    };

    // 屏幕中心确认弹窗
    function showCenterConfirm(message, callback) {
        let modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.left = '0';
        modal.style.top = '0';
        modal.style.width = '100vw';
        modal.style.height = '100vh';
        modal.style.background = 'rgba(0,0,0,0.18)';
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '9999';
        modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:340px;text-align:center;\">
            <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
            <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
            <button id='centerConfirmOk' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;margin-right:16px;'>确定</button>
            <button id='centerConfirmCancel' style='background:#eee;color:#444;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>取消</button>
        </div>`;
        document.body.appendChild(modal);
        document.getElementById('centerConfirmOk').onclick = function() {
            document.body.removeChild(modal);
            if (callback) callback(true);
        };
        document.getElementById('centerConfirmCancel').onclick = function() {
            document.body.removeChild(modal);
            if (callback) callback(false);
        };
    }

    // 屏幕中心提示弹窗
    function showCenterModal(message, callback) {
        let modal = document.createElement('div');
        modal.style.position = 'fixed';
        modal.style.left = '0';
        modal.style.top = '0';
        modal.style.width = '100vw';
        modal.style.height = '100vh';
        modal.style.background = 'rgba(0,0,0,0.18)';
        modal.style.display = 'flex';
        modal.style.alignItems = 'center';
        modal.style.justifyContent = 'center';
        modal.style.zIndex = '9999';
        modal.innerHTML = `<div style=\"background:#fff;border-radius:12px;box-shadow:0 4px 24px #0002;padding:32px 36px;min-width:320px;text-align:center;\">
            <div style='font-size:20px;font-weight:600;margin-bottom:12px;color:#388e3c;'>提示</div>
            <div style='font-size:16px;margin-bottom:24px;'>${message}</div>
            <button id='centerModalBtn' style='background:#4caf50;color:#fff;border:none;border-radius:6px;padding:8px 32px;font-size:16px;cursor:pointer;'>确定</button>
        </div>`;
        document.body.appendChild(modal);
        document.getElementById('centerModalBtn').onclick = function() {
            document.body.removeChild(modal);
            if (callback) callback();
        };
    }
}); 